package FlickrGeoTagr.Flickr {
	
	import com.adobe.webapis.flickr.*;
	import com.adobe.webapis.flickr.events.FlickrResultEvent;
	import com.adobe.webapis.flickr.methodgroups.helpers.PhotoSearchParams;
	
	import flash.events.*;
	
	public class FlickrPhotos extends EventDispatcher {
		
		private var _fs:FlickrService;
		private var _authorization:FlickrAuthorization;
		
		public var PhotoArray:Array;
		
		private var _log:Array;
		
		public function FlickrPhotos(authorization:FlickrAuthorization) {
			_authorization = authorization;
			
			_fs = new FlickrService(_authorization.API_KEY);
			_fs.secret = _authorization.SECRET;
			_fs.token = _authorization.AuthToken;
			_fs.permission = AuthPerm.WRITE;
		}
		
		public function loadWithLog(log:Array):void {
			_log = log;
			
			_fs.addEventListener(FlickrResultEvent.PHOTOS_SEARCH, handlePhotosReceived);
			
			var params:PhotoSearchParams = new PhotoSearchParams();
			params.user_id = "me";
			params.min_taken_date = new Date(_log[0].OffsetTime);
			params.max_taken_date = new Date(_log[_log.length-1].OffsetTime);
			params.sort = "date-taken-asc";
			params.extras = "date_taken";
			
			_fs.photos.searchWithParamHelper(params);
		}
		
		private function handlePhotosReceived(event:FlickrResultEvent):void {
			_fs.removeEventListener(FlickrResultEvent.PHOTOS_SEARCH, handlePhotosReceived);
			
			var photoList:PagedPhotoList = event.data.photos as PagedPhotoList;
			
			PhotoArray = new Array();
			
			var currentLogIndex:Number = 0;
			
			for each (var photo:Photo in photoList.photos) {
				var matchedLogId:Number = -1;
				
				for (var i:Number = currentLogIndex; i < _log.length; i++) {
					var offsetTime:Date = new Date(_log[i].OffsetTime);
					if (offsetTime.getTime() > photo.dateTaken.getTime()) {
						matchedLogId = _log[i].Id;
						currentLogIndex = i;
						break;
					}
				}
				
				var photoURL:String = "http://farm" + photo.farmId + ".static.flickr.com/" + photo.server + "/" + photo.id + "_" + photo.secret + "_s.jpg";
				PhotoArray.push({Id: photo.id, PhotoURL: photoURL, Date: photo.dateTaken, LogId: matchedLogId});
			}
			this.dispatchEvent(new Event(Event.COMPLETE));
		}
		
		public function processPhotos():void {

		}
	}
}